package com.song.osclient.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

import com.song.osclient.App;
import com.song.osclient.R;

/**
 * Created by Administrator on 2015/11/4.
 */
public class ScreenOverlay extends View {
    private RectF rectF;
    private Paint paint;
    private Bitmap rectBitmap;
    private Bitmap lineBitmap;
    private int lineOffset = 2;
    private int rectBitmapWidth;
    private int rectBitmapHeight;

    public ScreenOverlay(Context context) {
        super(context);
    }

    public ScreenOverlay(Context context, AttributeSet attrs) {
        super(context, attrs);
        initPoint();
    }

    public ScreenOverlay(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);
        canvas.drawBitmap(rectBitmap, rectF.left, rectF.top, paint);
        canvas.drawBitmap(lineBitmap, null, getDstRect(rectF, lineOffset), paint);
        lineOffset = lineOffset >= rectBitmapHeight - 10 ? 10 : lineOffset + 2;
        invalidate();
    }

    private void initPoint() {
        rectBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.qr_capture);
        lineBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.qr_scan_line);
        int mScreenWidth = App.getScreenWidth();
        int mScreenHeight = App.getScreenHeight();
        rectBitmapWidth = rectBitmap.getWidth();
        rectBitmapHeight = rectBitmap.getHeight();
        float left = (mScreenWidth - rectBitmapWidth) / 2;
        float top = (mScreenHeight - rectBitmapHeight - 20) / 2;
        float right = left + rectBitmapWidth;
        float bottom = top + rectBitmapHeight;
        rectF = new RectF(left, top, right, bottom);

        paint = new Paint();
    }

    private Rect getDstRect(RectF rectF, int offset) {
        Rect rect = new Rect();
        rect.left = (int) rectF.left;
        rect.top = (int) rectF.top + offset;
        rect.bottom = rect.top + App.dp2Px(2);
        rect.right = (int) (rectF.left + rectBitmapWidth);
        return rect;
    }

    public RectF getPreviewRectF() {
        return rectF;
    }

    public Rect getPreviewRect() {
        Rect rect = new Rect();
        rectF.round(rect);
        return rect;
    }
    public void stopScan(){
        
    }
}
